package com.abel.main;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 消息消费者
 */
public class MessageConsumer {

    public static String getMessage() {

        //消息链接工厂
        ConnectionFactory factory = null;

        //链接
        Connection connection = null;

        //会话
        Session session = null;

        //消费目的地
        Destination destination = null;

        //消费者
        javax.jms.MessageConsumer consumer = null;

        Message message = null;

        String messageStr = null;
        try {
            factory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.26.50:61616");
            connection = factory.createConnection();
            // 消息的消费者必须启动连接,否则无法处理消息
            connection.start();
            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            destination = session.createQueue("first-queue");
            consumer = session.createConsumer(destination);
            message = consumer.receive();
            message.acknowledge();
            messageStr = ((TextMessage)message).getText();
            System.out.println(messageStr);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

        return messageStr;

    }

    public static void main(String[] args) {
        System.out.println("消息内容是：" + getMessage());
    }

}
